package com.example.notepad.diary

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.notepad.R
import java.text.SimpleDateFormat
import java.util.Date

class EditDiaryActivity : AppCompatActivity() {
    private lateinit var editDiary: EditText
    private lateinit var btnSave: Button
    private lateinit var btnDelete: Button
    private lateinit var diaryText: String
    private lateinit var diaryTime: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_diary)

        editDiary = findViewById(R.id.editDiary)
        btnSave = findViewById(R.id.btnSave)
        btnDelete = findViewById(R.id.btnDelete)

        // 获取 Intent 中的数据
        diaryText = intent.getStringExtra("diaryText") ?: ""
        diaryTime = intent.getStringExtra("diaryTime") ?: ""

        // 设置 EditText 内容
        editDiary.setText(diaryText)

        // 保存按钮点击事件
        btnSave.setOnClickListener {
            val updatedText = editDiary.text.toString()
            if (updatedText.isNotEmpty()) {
                updateDiary(diaryTime, updatedText)
                Toast.makeText(this, "日记更新成功", Toast.LENGTH_SHORT).show()
                finish() // 返回到日记列表
            }
        }

        // 删除按钮点击事件
        btnDelete.setOnClickListener {
            deleteDiary(diaryTime)
            Toast.makeText(this, "日记删除成功", Toast.LENGTH_SHORT).show()
            finish() // 返回到日记列表
        }
    }

    private fun updateDiary(oldKey: String, newText: String) {
        val sharedPreferences = getSharedPreferences("DiaryPrefs", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        // 使用新的时间为键
        val newTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
        editor.remove(oldKey) // 删除旧条目
        editor.putString(newTime, newText) // 添加新条目
        editor.apply()
    }

    private fun deleteDiary(key: String) {
        val sharedPreferences = getSharedPreferences("DiaryPrefs", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.remove(key) // 删除条目
        editor.apply()
    }
}